package me.zhengjie.modules.business.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.thoughtworks.xstream.XStream;
import me.zhengjie.config.WxOfficialConfig;
import me.zhengjie.modules.business.message.*;
import me.zhengjie.modules.business.service.OfficialService;
import me.zhengjie.modules.business.service.dto.AccessToken;
import me.zhengjie.modules.business.vo.TemplateData;
import me.zhengjie.modules.business.vo.TemplateMessage;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OfficialServiceImpl implements OfficialService{

    private static AccessToken at;

    /**
     * description 解析请求方法，并返回数据
     * @param requestMap
     * @return String
     * @author churuitao
     * @date 2020年02月10日 10:04
     */
    @Override
    public String parseMessage(Map<String, String> requestMap){
        BaseMessage msg = null;
        String msgType = requestMap.get("MsgType");
        switch (msgType){
            case "text" :
                msg = handelTextRequest(requestMap);
                break;
            case "voice" :

                break;
            case "video" :

                break;
            case "shortvideo" :

                break;
            case "location" :

                break;
            case "link" :

                break;
                default:
                    break;
        }
        if(msg!=null) {
            return beanTOXml(msg);
        }
        return null;
    }
    /**
     *
     * @description 处理文字消息
     * @param requestMap 参数
     * @return
     * @author churuitao
     * @date 2020年01月27日 21:10
     */
    @Override
    public BaseMessage handelTextRequest(Map<String, String> requestMap) {
        if("图文".equals(requestMap.get("Content"))){
            List<Article> articles = new ArrayList<>();
            articles.add(new Article("这是图文消息的title","这是图文消息的description","http://mmbiz.qpic.cn/mmbiz_jpg/Z21h1h3vY5H4A52kcgKpZAhOZYMibicvxghYDBfBPMrb1sicTJmEUMyMbiajYXtT0yjjVBE91ibeb8XFhauNs2KVpLA/0","http://www.baidu.com"));
            return new NewsMessage(requestMap, articles);
        }else if("token".equals(requestMap.get("Content"))){
            return new TextMessage(requestMap,"获取token成功："+ this.getAccessToken());
        }else if("模板消息".equals(requestMap.get("Content"))){
            TemplateMessage templateMessage = new TemplateMessage();
            templateMessage.setTouser("o7dEEs3uH6mBTme9uHDE6nM2LgPI");
            templateMessage.setTemplate_id("0dIiGHT6M4MDZ9C0Op2Vy72qYsbOww9W3udjq2n4rrQ");
            templateMessage.setTopcolor("#FF0000");
            templateMessage.setUrl("http://www.baidu.com\\");

//            Map<String, String> miniprogramMap = new HashMap<>();
//            miniprogramMap.put("appid","wxa73343c52dcba7da");
//            miniprogramMap.put("pagepath","");
//            templateMessage.setMiniprogram(miniprogramMap);

            HashMap<String, TemplateData> hashMap = new HashMap<>();
            hashMap.put("first",new TemplateData("有一个消息","#173177"));
            hashMap.put("company",new TemplateData("牛牛牛公司","#173177"));
            hashMap.put("time",new TemplateData("2020-1-28","#173177"));
            hashMap.put("result",new TemplateData("录取成功","#173177"));
            hashMap.put("remark",new TemplateData("恭喜","#173177"));
            templateMessage.setData(hashMap);
            String params = JSONUtil.parseObj(templateMessage).toString();;
            String jsonResult = HttpUtil.post(WxOfficialConfig.SEND_TEMPLATE_URL+getAccessToken(),params);
            return new TextMessage(requestMap,jsonResult);
        }else if("设置行业".equals(requestMap.get("Content"))){
            String params = "{\"industry_id1\":1,\"industry_id2\":2}\n";
            String jsonResult = HttpUtil.post(WxOfficialConfig.SEND_TEMPLATE_URL+getAccessToken(),params);
            return new TextMessage(requestMap,jsonResult);
        }
        //默认返回发送的消息
        return new TextMessage(requestMap,requestMap.get("Content"));
    }
    /**
     *
     * @description Bean 变成 xml
     * @param msg 消息类
     * @return String
     * @author churuitao
     * @date 2020年01月27日 23:38
     */
    @Override
    public String beanTOXml(BaseMessage msg){
        XStream stream = new XStream();
        stream.processAnnotations(TextMessage.class);
        stream.processAnnotations(ImageMessage.class);
        stream.processAnnotations(MusicMessage.class);
        stream.processAnnotations(NewsMessage.class);
        stream.processAnnotations(VideoMessage.class);
        stream.processAnnotations(VoiceMessage.class);
        String xml = stream.toXML(msg);
        System.out.println(xml);
        return xml;
    }
    /**
     *
     * @description 获取token
     * @author churuitao
     * @date 2020年01月28日 14:19
     */
    private static void getToken(){
        String response = HttpUtil.get(WxOfficialConfig.GET_TOKEN_URL.replace("APPID",WxOfficialConfig.APPID).replace("APPSECRET",WxOfficialConfig.APPSECRET));
        JSONObject jsonObject = JSONUtil.parseObj(response);
        String accessToken = jsonObject.getStr("access_token");
        String expiresIn = jsonObject.getStr("expires_in");
        at = new AccessToken(accessToken, expiresIn);
    }

    /**
     * description 获取token
     * @author churuitao
     * date 2020年02月10日 10:29
     */
    @Override
    public String getAccessToken(){
        if(at==null || at.isExpired()){
            getToken();
        }
        return at.getAccessToken();
    }
}
